package cn.my.learning.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by Leo on 2017/5/3.
 * WebSecurityConfig
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    private final static String[] excludePath = {"/bootstrap/**","/cropper/**","/css/**","/editor/**","/font-awesome/**,/fonts/**","/image/**","/js/**","/sweetAlert/**","/text/**"};

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(excludePath);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .and()
            .formLogin()
                .loginPage("/userLogin")
                .successHandler(loginSuccessHandler())
                .permitAll()
                .and()
            .logout()
                .logoutSuccessHandler(logoutSuccessHandler())
                .permitAll()
                .invalidateHttpSession(true)
                .and();
    }

    @Bean
    public LoginSuccessHandler loginSuccessHandler(){
        return new LoginSuccessHandler();
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() { return new LogoutSuccessHandler(); }
}
